<template>
  <ion-page>
       <ion-alert
        :is-open="newalert"
        :header="Data.alertPacketTypeName"
        :sub-header="Data.alertInstrumentName"
        :message="`${Data.triggerName},RA: ${Data.alertRaCenter},Dec: ${Data.alertDecCenter},ERR: ${Data.alertLocalisationError}\n,${Data.triggerTime}UTC`"
        :buttons="alertButtons"
        @didDismiss="newalert = false"     
        >
      </ion-alert> 
  </ion-page>
</template>
   
  <script setup>
  import {  onMounted,onUnmounted,ref,} from 'vue';
  import { IonPage,IonAlert} from '@ionic/vue';
  import service from '@/api/api';
  import { useRouter } from 'vue-router';
  const router = useRouter();
  
  const alertButtons = [
    {
      text: 'Cancel',
      role: 'cancel',
      handler: () => {
      },
    },
    {
      text: 'Enter',
      role: 'confirm',
      handler: () => {
        goToDetail(Data.value.triggerName)
      },
    },
  ];
  const goToDetail = (triggerName) => {
      router.push({
      name: 'eventdetails',
      params: { triggerName }, 
    });
  };
const newalert=ref(false)
const alertData=ref('')   
const oldalertData = ref(localStorage.getItem('lastAlertId') || '');
const Data=ref('')
  const fetchData=async () => {
    try {    
      const response = await service.post('/alertApi/getAlerts',{length:'10'});
      Data.value = response.data.data.list[0];
      alertData.value =  String(response.data.data.list[0].alertId);
      localStorage.setItem('lastAlertId', alertData.value);
      if(alertData.value!==oldalertData.value){
        newalert.value = true;        
        console.log(response.data);
      }
      oldalertData.value=alertData.value
                  
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  }
  onMounted(fetchData);
  onMounted(() => {
  const intervalId = setInterval(async () => {
    fetchData()
  }, 60000);

  // 清理轮询
  onUnmounted(() => {
    clearInterval(intervalId);
  });
 });





  </script>